package com.hxut.mrs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxut.mrs.domain.LoginUser;
import com.hxut.mrs.domain.User;
import com.hxut.mrs.mapper.MenuMapper;
import com.hxut.mrs.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * description: UserDetailsServiceImpl
 * date: 2022/7/7 10:10
 * author: MR.孙
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        //如果查询不到数据就抛出异常给出提示
        if (Objects.isNull(user)){
            throw  new RuntimeException("用户名或密码错误");
        }

        //TODO 根据用户查询权限信息,添加到LoginUser中
        // ArrayList<String> lists = new ArrayList<>(Arrays.asList("test","admin"));

        List<String> lists=menuMapper.selectPermsByUserId(user.getId());
        //封装成UserDetails对象返回
        return new LoginUser(user,lists);
    }
}
